package org.springblade.modules.door.service;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.door.dto.DoorOperateNotifyDto;
import org.springblade.modules.door.vo.DoorOperateVo;
import org.springblade.modules.door.dto.OrderNotifyDto;
import org.springblade.modules.door.entity.ThirdDoorOperate;
import org.springblade.modules.door.entity.ThirdOrder;
import org.springblade.modules.door.entity.ThirdOrderGoods;
import org.springblade.modules.door.mapper.ThirdDoorOperateMapper;
import org.springblade.modules.door.mapper.ThirdOrderGoodsMapper;
import org.springblade.modules.door.mapper.ThirdOrderMapper;
import org.springblade.modules.door.vo.DeviceOrderVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class XiaomaiService {
	@Resource
	private ThirdOrderMapper thirdOrderMapper;
	@Resource
	private ThirdOrderGoodsMapper thirdOrderGoodsMapper;
	@Resource
	private ThirdDoorOperateMapper thirdDoorOperateMapper;


	public Boolean orderNotify(OrderNotifyDto orderNotifyDto) {
		log.info("小麦订单回调参数{}", JSON.toJSONString(orderNotifyDto));
		String orderCode = orderNotifyDto.getOrderCode();
		LambdaQueryWrapper<ThirdOrder> orderWrapper = Wrappers.lambdaQuery();
		orderWrapper.eq(ThirdOrder::getOrderCode, orderCode).last("LIMIT 1");
		ThirdOrder thirdOrder = thirdOrderMapper.selectOne(orderWrapper);
		if(null == thirdOrder){
			ThirdOrder thirdOrderInsert = new ThirdOrder();
			thirdOrderInsert.setOrderCode(orderNotifyDto.getOrderCode());
			thirdOrderInsert.setDeviceCode(orderNotifyDto.getDeviceCode());
			thirdOrderInsert.setOrderAmount(orderNotifyDto.getOrderAmount());
			thirdOrderInsert.setProductAmount(orderNotifyDto.getProductAmount());
			thirdOrderInsert.setPromotionAmount(orderNotifyDto.getPromotionAmount());
			thirdOrderInsert.setUserId(orderNotifyDto.getUserId());
			thirdOrderInsert.setCreateTime(new Date());
			thirdOrderInsert.setUpdateTime(new Date());
			thirdOrderInsert.setOrderState(ThirdOrder.STATE_INIT);
			thirdOrderInsert.setRequestSerial(orderNotifyDto.getRequestSerial());
			thirdOrderMapper.insert(thirdOrderInsert);
			String goodsList = orderNotifyDto.getGoodsList();
			List<OrderNotifyDto.Goods> goodsLists = JSON.parseArray(goodsList, OrderNotifyDto.Goods.class);
			//保存商品数据
			for (OrderNotifyDto.Goods goods : goodsLists) {
				ThirdOrderGoods thirdOrderGoods = new ThirdOrderGoods();
				thirdOrderGoods.setOrderCode(orderCode);
				thirdOrderGoods.setGoodsAmount(goods.getGoodsAmount());
				thirdOrderGoods.setGoodsNum(goods.getGoodsNum());
				thirdOrderGoods.setGoodsPrice(goods.getGoodsPrice());
				thirdOrderGoods.setGoodsPromotionAmount(goods.getGoodsPromotionAmount());
				thirdOrderGoods.setCreateTime(new Date());
				thirdOrderGoods.setGoodsId(goods.getGoodsId());
				thirdOrderGoods.setName(goods.getName());
				thirdOrderGoodsMapper.insert(thirdOrderGoods);
			}

		}
		return true;
	}

	public Object getOrderInfo(String deviceCode,String requestSerial) {
		log.info("小麦机器查询订单{}",deviceCode+"|"+requestSerial);
		Date end = new Date();
		Date begin = DateUtil.plusMinutes(end, -30);
		LambdaQueryWrapper<ThirdOrder> orderWrapper = Wrappers.lambdaQuery();
		orderWrapper.eq(ThirdOrder::getDeviceCode, deviceCode)
			.between(ThirdOrder::getCreateTime,begin,end)
			.eq(ThirdOrder::getOrderState,ThirdOrder.STATE_INIT)
			.eq(ThirdOrder::getRequestSerial,requestSerial)
			.orderByDesc(ThirdOrder::getCreateTime)
			.last("LIMIT 1");
		ThirdOrder thirdOrder = thirdOrderMapper.selectOne(orderWrapper);
		if(null == thirdOrder){
			return null;
		}
		DeviceOrderVO copy = BeanUtil.copy(thirdOrder, DeviceOrderVO.class);
		LambdaQueryWrapper<ThirdOrderGoods> goodsWrapper = Wrappers.lambdaQuery();
		goodsWrapper.eq(ThirdOrderGoods::getOrderCode, thirdOrder.getOrderCode());
		List<ThirdOrderGoods> thirdOrderGoods = thirdOrderGoodsMapper.selectList(goodsWrapper);
		List<DeviceOrderVO.Goods> collect = thirdOrderGoods.stream().map(x -> BeanUtil.copy(x, DeviceOrderVO.Goods.class)).collect(Collectors.toList());
		copy.setGoodsList(collect);
		log.info("小麦机器查询订单{}====>{}",deviceCode+"|"+requestSerial,JSON.toJSONString(copy));
		return copy;
	}

	public int orderComplete(String deviceCode,String orderCode) {
		log.info("小麦订单完成接口{}",orderCode);
		LambdaQueryWrapper<ThirdOrder> orderWrapper = Wrappers.lambdaQuery();
		orderWrapper.eq(ThirdOrder::getOrderCode, orderCode)
			.eq(ThirdOrder::getDeviceCode,deviceCode)
			.last("LIMIT 1");
		ThirdOrder thirdOrder = thirdOrderMapper.selectOne(orderWrapper);
		thirdOrder.setOrderState(ThirdOrder.STATE_SUCCESS);
		thirdOrder.setUpdateTime(new Date());
		return thirdOrderMapper.updateById(thirdOrder);
	}

	public boolean doorOperateNotify(String s) {
		Map<String, String> stringStringMap = parseParam(s);
		DoorOperateNotifyDto doorOperateNotifyDto = JSON.parseObject(JSON.toJSONString(stringStringMap), DoorOperateNotifyDto.class);
		LambdaQueryWrapper<ThirdDoorOperate> doorWrapper = Wrappers.lambdaQuery();
		doorWrapper.eq(ThirdDoorOperate::getDeviceCode, doorOperateNotifyDto.getDeviceCode())
			.last("LIMIT 1");
		ThirdDoorOperate doorOperate = thirdDoorOperateMapper.selectOne(doorWrapper);
		if(Func.isEmpty(doorOperate)){
			ThirdDoorOperate thirdDoorOperate = new ThirdDoorOperate();
			thirdDoorOperate.setUserId(doorOperateNotifyDto.getUserId());
			thirdDoorOperate.setDeviceCode(doorOperateNotifyDto.getDeviceCode());
			thirdDoorOperate.setDoorState(doorOperateNotifyDto.getIsOpenDoor()==1?0:1);
			thirdDoorOperate.setCreateTime(new Date());
			thirdDoorOperate.setUpdateTime(new Date());
			thirdDoorOperate.setOperateTime(new Date(doorOperateNotifyDto.getTimeStamp()));
			thirdDoorOperate.setRequestSerial(doorOperateNotifyDto.getRequestSerial());
			thirdDoorOperateMapper.insert(thirdDoorOperate);
		}else {
			doorOperate.setUserId(doorOperateNotifyDto.getUserId());
			doorOperate.setOperateTime(new Date(doorOperateNotifyDto.getTimeStamp()));
			doorOperate.setUpdateTime(new Date());
			doorOperate.setDoorState(doorOperateNotifyDto.getIsOpenDoor()==1?0:1);
			doorOperate.setRequestSerial(doorOperateNotifyDto.getRequestSerial());
			thirdDoorOperateMapper.updateById(doorOperate);
		}
		return true;
	}

	private Map<String, String> parseParam(String urlVariables){
		return Arrays.stream(urlVariables.split("&"))
			.map(pair -> pair.split("=", 2))
			.collect(Collectors.toMap(
				arr -> arr[0],
				arr -> arr.length > 1 ? arr[1] : "",
				(oldVal, newVal) -> oldVal // 如果 key 重复，保留旧值
			));
	}

	public Object getDoorState(String deviceCode,String requestSerial) {
		log.info("小麦查询开关门状态{}",deviceCode+"|"+requestSerial);
		LambdaQueryWrapper<ThirdDoorOperate> doorWrapper = Wrappers.lambdaQuery();
		doorWrapper.eq(ThirdDoorOperate::getDeviceCode, deviceCode)
		.eq(ThirdDoorOperate::getRequestSerial, requestSerial)
			.last("LIMIT 1");
		ThirdDoorOperate doorOperate = thirdDoorOperateMapper.selectOne(doorWrapper);
		if(Func.isEmpty(doorOperate)){
			log.info("小麦查询开关门状态返回{}===>{}",deviceCode,null);
			return null;
		}
		DoorOperateVo doorOperateVo = new DoorOperateVo();
		doorOperateVo.setUserId(doorOperate.getUserId());
		doorOperateVo.setDeviceCode(doorOperate.getDeviceCode());
		doorOperateVo.setDoorState(doorOperate.getDoorState());
		doorOperateVo.setOperateTime(doorOperate.getOperateTime());
		doorOperateVo.setRequestSerial(doorOperate.getRequestSerial());
		doorOperateVo.isCloseDoor();
		log.info("小麦查询开关门状态返回{}===>{}",deviceCode+"|"+requestSerial,JSON.toJSONString(doorOperateVo));
		return doorOperateVo;
	}
}
